import { ITableData } from "../../inters/InterfaceApi";
import { convertMgr } from "./ConvertMgr";

export class LanguageMgr {
    private static _inst: LanguageMgr;
    static get inst(): LanguageMgr {
        LanguageMgr._inst = LanguageMgr._inst || new LanguageMgr();
        return LanguageMgr._inst;
    }

    /** 有可能存在的语言类型列表；eg: ['cn','en'] */
    langTypes: string[];
    /** 所有的语言数据 */
    langData: { [lang: string]: any };
    /** 字体的数据，方便最后一起导出 */
    fontHash: any;
    /** 导出的文件名 */
    exportName: string;

    constructor() {
        this.init()
    }

    init() {
        this.exportName = ''
        this.langTypes = [];
        this.langData = {};
        this.fontHash = {};
    }

    addLangList(type: string) {
        if (this.langTypes.indexOf(type) < 0) {
            this.langTypes.push(type);
        }
    }

    addLang(msg: string, key: string, lang: string, font: string) {
        if (!msg) return;
        this.langData[lang] || (this.langData[lang] = {});
        this.langData[lang][key] = msg;

        if (!this.fontHash) this.fontHash = {};
        if (!!font) {
            var fonts: string[];
            if (font.indexOf(",") != -1) {
                fonts = font.split(",");
            } else {
                fonts = [font];
            }
            for (let i = 0; i < fonts.length; i++) {
                font = fonts[i];
                if (!this.fontHash[font]) this.fontHash[font] = {};
                if (!this.fontHash[font][lang]) this.fontHash[font][lang] = "";
                this.fontHash[font][lang] += msg;
            }
        }
    }

    /** 生成导出文件前，需要调用 */
    finish() {
        // let temp = tableData.tabName.split("_");
        let platStr = ''
        // if (temp.length > 1) {
        //     platStr = "_" + temp[temp.length - 1];
        // }

        for (let fontName in this.fontHash) {
            let font = this.fontHash[fontName];
            for (let lang in font) {
                let txt = font[lang];
                let fontStr = txt.replace(/(.)(?=.*\1)/g, "");
                font[lang] = fontStr;
            }
        }

        for (let lang in this.langData) {
            let langObj = this.langData[lang];
            let tempTableData: ITableData = {
                type: "lang",
                keys: [],
                tableName: this.exportName,
                data: langObj,
                errLog: [],
                plat: platStr
            }
            convertMgr.crtConvert.addTableData(tempTableData, this.exportName + "_" + lang);
        }
    }

    getJson(lang: string) {
        return this.langData[lang];
    }

    getFont() {

    }

}

export var langMgr = LanguageMgr.inst;
